<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>管理员购票信息</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            margin: 0;
            padding: 20px;
        }

        h1 {
            color: #333;
            text-align: center;
        }

        a {
            display: inline-block;
            margin: 10px 5px;
            padding: 10px 20px;
            background-color: #007BFF;
            color: white;
            text-decoration: none;
            border-radius: 5px;
        }

        a:hover {
            background-color: #0056b3;
        }

        button {
            padding: 10px 20px;
            background-color: #28a745;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            margin: 5px;
        }

        button:hover {
            background-color: #218838;
        }

        form {
            background-color: white;
            padding: 20px;
            border-radius: 5px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            margin: 20px 0;
        }

        label {
            display: block;
            margin-bottom: 5px;
        }

        input[type="text"],
        input[type="number"] {
            width: 100%;
            padding: 10px;
            margin-bottom: 15px;
            border: 1px solid #ccc;
            border-radius: 5px;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }

        th, td {
            padding: 10px;
            border: 1px solid #ccc;
            text-align: center;
        }

        th {
            background-color: #007BFF;
            color: white;
        }

        tr:nth-child(even) {
            background-color: #f2f2f2;
        }

        .pagination {
            margin-top: 20px;
            text-align: center;
        }

        .pagination a {
            margin: 0 5px;
        }
    </style>
</head>
<body>
<h1>恭喜你，<span th:text="${username}"></span> 管理员登录成功！</h1>
<a th:href="@{/adminSuccessPage(username=${username}, page=0, size=10)}">用户信息</a>
<a th:href="@{/adminTicketsPage(username=${username}, page=0, size=10)}">购票信息</a>
<a th:href="@{/adminMoviesPage(username=${username}, page=0, size=10)}">电影信息</a>
<a th:href="@{/adminGenersPage(username=${username}, page=0, size=10)}">类别信息</a>
<a th:href="@{/adminDirectorsPage(username=${username}, page=0, size=10)}">导演信息</a>
<a th:href="@{/adminActorsPage(username=${username}, page=0, size=10)}">演员信息</a>
<a th:href="@{/adminReviewsPage(username=${username}, page=0, size=10)}">评论信息</a>

<!-- 添加添加购票按钮 -->
<button onclick="showAddTicketForm()">添加购票</button>

<div id="addTicketForm" style="display: none;">
    <h3>添加购票信息</h3>
    <form id="addTicketFormData">
        <input type="hidden" id="addUuid" name="uuid">
        <label for="addUname">用户名:</label>
        <input type="text" id="addUname" name="uname" required><br>
        <label for="addMname">电影名称:</label>
        <input type="text" id="addMname" name="mname" required onchange="getMoviePrice(this.value)"><br>
        <label for="addPrice">价格:</label>
        <input type="number" id="addPrice" name="price" readonly><br>
        <label for="addCount">数量:</label>
        <input type="number" id="addCount" name="count" min="1" value="1" required><br>
        <input type="hidden" id="addOtime" name="otime">
        <button type="button" onclick="submitAddTicketForm()">提交</button>
        <button type="button" onclick="cancelAddTicketForm()">取消</button>
    </form>
</div>

<!-- 修改购票表单 -->
<div id="editTicketForm" style="display: none;">
    <h3>修改购票信息</h3>
    <form id="editTicketFormData">
        <input type="hidden" id="editUuid" name="uuid">
        <input type="hidden" id="editTid" name="tid">
        <label for="editUname">用户名:</label>
        <input type="text" id="editUname" name="uname" required><br>
        <label for="editMname">电影名称:</label>
        <input type="text" id="editMname" name="mname" required onchange="getMoviePrice(this.value)"><br>
        <label for="editPrice">价格:</label>
        <input type="number" id="editPrice" name="price" readonly><br>
        <label for="editCount">数量:</label>
        <input type="number" id="editCount" name="count" min="1" value="1" required><br>
        <input type="hidden" id="editOtime" name="otime">
        <button type="button" onclick="submitEditTicketForm()">提交</button>
        <button type="button" onclick="cancelEditTicketForm()">取消</button>
    </form>
</div>

<!-- 添加搜索框和搜索按钮 -->
<form id="searchForm">
    <input type="hidden" th:name="username" th:value="${username}">
    <label for="searchUname">根据用户名搜索:</label>
    <input type="text" id="searchUname" name="uname">
    <input type="button" value="搜索" onclick="searchTickets()">
</form>

<h2>购票信息列表</h2>
<table>
    <thead>
    <tr>
        <th>订单号</th>
        <th>用户id</th>
        <th>用户名</th>
        <th>电影名称</th>
        <th>价格</th>
        <th>数量</th>
        <th>总价</th>
        <th>购票时间</th>
    </tr>
    </thead>
    <tbody id="ticketTableBody">
    <tr th:each="ticket : ${tickets}">
        <td th:text="${ticket.tid}"></td>
        <td th:text="${ticket.uuid}"></td>
        <td th:text="${ticket.uname}"></td>
        <td th:text="${ticket.mname}"></td>
        <td th:text="${ticket.price}"></td>
        <td th:text="${ticket.count}"></td>
        <td th:text="${ticket.totalprice}"></td>
        <td th:text="${ticket.otime}"></td>
        <td>
            <button th:onclick="'showEditTicketForm(' + ${ticket.tid} + ')'">修改</button> <!-- 添加修改按钮 -->
            <button th:onclick="'deleteTicket(' + ${ticket.tid} + ')'">删除</button> <!-- 添加删除按钮 -->
        </td>
    </tr>
    </tbody>
</table>

<!-- 分页导航栏 -->
<div class="pagination">
    <!-- 首页 -->
    <a th:href="@{/adminTicketsPage(username=${username}, page=0, size=${pageSize})}">首页</a>

    <!-- 上一页 -->
    <a th:if="${currentPage > 0}" th:href="@{/adminTicketsPage(username=${username}, page=${currentPage - 1}, size=${pageSize})}">上一页</a>

    <!-- 下一页 -->
    <a th:if="${currentPage < totalPages - 1}" th:href="@{/adminTicketsPage(username=${username}, page=${currentPage + 1}, size=${pageSize})}">下一页</a>

    <!-- 末页 -->
    <a th:href="@{/adminTicketsPage(username=${username}, page=${totalPages - 1}, size=${pageSize})}">末页</a>

    <!-- 显示当前页和总页数 -->
    <span>当前页: <span th:text="${currentPage + 1}"></span> / 总页数: <span th:text="${totalPages}"></span></span>
    <form th:action="@{/adminTicketsPage}" method="get">
        <input type="hidden" th:name="username" th:value="${username}">
        <input type="hidden" th:name="size" th:value="${pageSize}">
        <label for="pageNumber">跳转到页数:</label>
        <input type="number" id="pageNumber" name="page" min="0" th:max="${totalPages - 1}" required>
        <input type="submit" value="跳转">
    </form>
</div>

<script>

    function searchTickets() {
        const uname = document.getElementById('searchUname').value;
        const url = `/ticket/searchTicket?uname=${uname}`;

        fetch(url)
            .then(response => response.json())
            .then(data => {
                const ticketTableBody = document.getElementById('ticketTableBody');
                ticketTableBody.innerHTML = '';

                if (data.success) {
                    const tickets = data.tickets;
                    tickets.forEach(ticket => {
                        const row = document.createElement('tr');
                        row.innerHTML = `
                                <td>${ticket.tid}</td>
                                <td>${ticket.uuid}</td>
                                <td>${ticket.uname}</td>
                                <td>${ticket.mname}</td>
                                <td>${ticket.price}</td>
                                <td>${ticket.count}</td>
                                <td>${ticket.totalprice}</td>
                                <td>${ticket.otime}</td>
                            `;
                        ticketTableBody.appendChild(row);
                    });
                } else {
                    const row = document.createElement('tr');
                    row.innerHTML = `<td colspan="8">${data.error}</td>`;
                    ticketTableBody.appendChild(row);
                }
            })
            .catch(error => {
                console.error('搜索出错:', error);
            });
    }

    function showAddTicketForm() {
        document.getElementById('addTicketForm').style.display = 'block';
    }

    function cancelAddTicketForm() {
        document.getElementById('addTicketForm').style.display = 'none';
    }

    function getMoviePrice(movieName) {
        if (movieName) {
            fetch(`/movie/getMoviePrice?mname=${movieName}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        document.getElementById('addPrice').value = data.price;
                    } else {
                        document.getElementById('addPrice').value = '';
                    }
                })
                .catch(error => {
                    console.error('获取电影价格出错:', error);
                    document.getElementById('addPrice').value = '';
                });
        } else {
            document.getElementById('addPrice').value = '';
        }
    }

    function getUserIdAndCalculateTotalPrice() {
        const uname = document.getElementById('addUname').value;
        var price = parseFloat(document.getElementById('addPrice').value);
        var count = parseInt(document.getElementById('addCount').value);

        // 获取用户的 uuid
        if (uname) {
            fetch(`/user/getUserId?uname=${uname}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        document.getElementById('addUuid').value = data.uuid;
                    } else {
                        document.getElementById('addUuid').value = '';
                    }
                })
                .catch(error => {
                    console.error('获取用户 ID 出错:', error);
                    document.getElementById('addUuid').value = '';
                });
        } else {
            document.getElementById('addUuid').value = '';
        }

        // 设置 otime
        const now = new Date();
        const otime = now.toISOString().slice(0, 19).replace('T', ' ');
        document.getElementById('addOtime').value = otime;
    }

    function submitAddTicketForm() {
        const form = document.getElementById('addTicketFormData');
        const formData = {
            uuid: form.addUuid.value,
            uname: form.addUname.value,
            mname: form.addMname.value,
            price: form.addPrice.value,
            count: form.addCount.value,
            otime: form.addOtime.value
        };

        fetch('/ticket/addTicket', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(formData)
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('购票添加成功');
                    cancelAddTicketForm();
                    searchTickets(); // 刷新列表
                } else {
                    alert('购票添加失败：' + data.message);
                }
            })
            .catch(error => {
                console.error('添加购票出错:', error);
                alert('添加购票出错，请稍后重试');
            });
    }

    // 在用户名和数量输入框添加 onchange 事件
    document.getElementById('addUname').onchange = getUserIdAndCalculateTotalPrice;
    document.getElementById('addCount').onchange = getUserIdAndCalculateTotalPrice;

    function showEditTicketForm(tid) {
        console.log('传入的订单号:', tid);
        fetch(`/ticket/infoTicket?tid=${tid}`) // 调用 TicketController 的 getUserInfo 方法
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const ticket = data.ticket;
                    document.getElementById('editTid').value = ticket.tid;
                    document.getElementById('editUuid').value = ticket.uuid;
                    document.getElementById('editUname').value = ticket.uname;
                    document.getElementById('editMname').value = ticket.mname;
                    document.getElementById('editPrice').value = ticket.price;
                    document.getElementById('editCount').value = ticket.count;
                    document.getElementById('editOtime').value = ticket.otime;
                    document.getElementById('editTicketForm').style.display = 'block';
                } else {
                    alert('获取购票信息失败：' + data.error);
                }
            })
            .catch(error => {
                console.error('获取购票信息出错:', error);
                alert('获取购票信息出错，请稍后重试');
            });
    }

    function submitEditTicketForm() {
        const form = document.getElementById('editTicketFormData');
        const formData = {
            uuid: form.editUuid.value,
            tid: form.editTid.value,
            uname: form.editUname.value,
            mname: form.editMname.value,
            price: form.editPrice.value,
            count: form.editCount.value,
            otime: form.editOtime.value
        };

        fetch('/ticket/updateTicket', {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(formData)
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('购票信息修改成功');
                    cancelEditTicketForm();
                    searchTickets(); // 刷新列表
                } else {
                    alert('购票信息修改失败：' + data.message);
                }
            })
            .catch(error => {
                console.error('修改购票信息出错:', error);
                alert('修改购票信息出错，请稍后重试');
            });
    }

    function cancelEditTicketForm() {
        document.getElementById('editTicketForm').style.display = 'none';
    }

    function deleteTicket(tid) {
        if (confirm('确定要删除该购票信息吗？')) {
            fetch(`/ticket/deleteTicket/${tid}`, {
                method: 'DELETE'
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert('购票信息删除成功');
                        searchTickets(); // 刷新列表
                    } else {
                        alert('购票信息删除失败：' + data.message);
                    }
                })
                .catch(error => {
                    console.error('删除购票信息出错:', error);
                    alert('删除购票信息出错，请稍后重试');
                });
        }
    }
</script>
</body>
</html>